import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchMedicineSettingPage extends StatefulWidget {
  const WatchMedicineSettingPage({super.key});

  @override
  State<WatchMedicineSettingPage> createState() => _WatchMedicineSettingPageState();
}

class _WatchMedicineSettingPageState extends State<WatchMedicineSettingPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址
  String _title = ""; //页面标题

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final _controller = Get.put(WatchSettingController());

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_title > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        Log.d("need close page: $need"),
        if (need == 2) {Get.back()}
      },
    );
    return Scaffold(
      appBar: AppBar(
        title: const Text("吃药提醒"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //开关
          Obx(
            () => SwitchListTile(
              dense: true,
              inactiveThumbColor: _unConfirmColor,
              inactiveTrackColor: _unConfirmColor.withAlpha(88),
              activeColor: _confirmColor,
              activeTrackColor: _confirmColor.withAlpha(88),
              title: Text("开关", style: _titleStyle),
              onChanged: (bool value) {
                var temp = _controller.medicineRemindBean.value;
                temp.isSwitch = value;
                _controller.updateMedicineRemindBean(temp);
              },
              value: _controller.medicineRemindBean.value.isSwitch,
            ),
          ),

          Obx(
            () => Visibility(
              visible: _controller.medicineRemindBean.value.isSwitch,
              child:
                  //开始时间
                  ListTile(
                title: Text("下一次吃药时间", style: _titleStyle),
                trailing: Obx(
                  () => Text(
                    "${_controller.medicineRemindBean.value.hour}:${_controller.medicineRemindBean.value.minute}",
                    style: _trailingStyle,
                  ),
                ),
                onTap: () {
                  _clickTime(_controller.medicineRemindBean.value.hour,
                      _controller.medicineRemindBean.value.minute);
                },
              ),
            ),
          ),

          //占位
          const Expanded(child: SizedBox()),
          //确认按钮
          Container(
            width: double.infinity,
            height: 46,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: TextButton(
              onPressed: () {
                _confirm();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
                foregroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
              child: const Text('确认'),
            ),
          ),
          const SizedBox(height: 60),
        ],
      ),
    );
  }

  _clickTime(int hour, int minute) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.HM,
      selectDate: PDuration(hour: hour, minute: minute),
      onConfirm: (p) {
        Log.d('开始时间选择器：$p');
        var temp = _controller.medicineRemindBean.value;
        temp.hour = p.hour ?? 0;
        temp.minute = p.minute ?? 0;
        _controller.updateMedicineRemindBean(temp);
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    List<int> result;
    var temp = _controller.medicineRemindBean.value;
    int resSwitch = (temp.isSwitch) ? 1 : 0;
    result = ProtocolDataUtil.instance!.medicineRemind(resSwitch, temp.hour, temp.minute);
    return result;
  }

}
